﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LumenWorks.Framework.IO.Csv;
using System.IO;

namespace SmartText.Converter
{
    class CSVToLua
    {
        private const string SRC_START =
            "{0} = \r\n";
        private const string SRC_BRACE_START =
            "{";
        private const string SRC_BRACE_END =
            "}";
        private const string SRC_CONTENT =
            "['{0}'] = {1},";

        public static string ConvertToLua(string sFileName, Encoding enc)
        {
            using (var reader = new CsvReader(new StreamReader(sFileName, enc), true))
            {
                var sbLua = new StringBuilder();
                var headers = reader.GetFieldHeaders();

                sbLua.AppendFormat(SRC_START, Path.GetFileNameWithoutExtension(sFileName));
                sbLua.AppendLine(SRC_BRACE_START);
                foreach (var line in reader)
                {
                    sbLua.AppendLine(Indent(4) + SRC_BRACE_START);
                    for (int i = 0; i < headers.Length; i++)
                    {
                        sbLua.AppendLine(Indent(8) + string.Format(SRC_CONTENT, headers[i], GetValue(line[i])));
                    }
                    sbLua.AppendLine(Indent(4) + SRC_BRACE_END + ",");
                }
                sbLua.AppendLine(SRC_BRACE_END);
                return sbLua.ToString();
            }
        }

        private static string Indent(int count)
        {
            return new String(' ', count);
        }

        private static string GetValue(string value)
        {
            double dNum;
            if (Double.TryParse(value, out dNum))
            {
                return value; ;
            }
            else
            {
                return "'" + value + "'";
            }
        }
   }
}
